package team.nmsg.ge.system.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import team.nmsg.ge.system.util.os.OSinfo;

/**
 * 脚本运行 辅助类
 * @author Guodeqi
 *
 */
public class NMSRunScriptUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(NMSRunScriptUtil.class);
	
	public static final String SCRIPT_SUFFIX_LINUX = ".sh";
	public static final String SCRIPT_SUFFIX_WINDOWS = ".bat";
	
	public static final String FILE_SEP = "/";
	
	
	/**
	 * 稍总结了一下：Windows下的批处理：cd /d %~dp0.%~dp0表示此批处理的目录，
	 * /d表示切换目录的同时也切换盘符.
	 * Linux下shell：cd 'dirname $0' ;
	 * 
	 * @param baseDir 脚本目录
	 * @param scriptName	脚本名称,不带后缀
	 * @return
	 * @throws IOException
	 * @throws InterruptedException
	 */
	public static boolean runScript( String dirPath, String scriptName ) throws IOException, InterruptedException{
		
		String scriptSuffix = "";
		String command = "";
		String userDir = System.getProperty("user.dir");
		userDir = userDir.replaceAll("\\\\", "/");
		if( OSinfo.isWindows() ){
			scriptSuffix = SCRIPT_SUFFIX_WINDOWS;
			command = "cmd /c \""+ dirPath+FILE_SEP +scriptName+scriptSuffix +"\"";
			
		}else if(  OSinfo.isLinux() ){
			
//			String command2 = "/bin/sh " + shpath +" " + var;
			
			scriptSuffix = SCRIPT_SUFFIX_LINUX;
			command = "chmod 777 "+ dirPath+FILE_SEP +scriptName+scriptSuffix ;
		}
		
		Runtime runtime = Runtime.getRuntime();
		Process exec = runtime.exec(command);
		exec.waitFor();
		int i = exec.exitValue();  //接收执行完毕的返回值
		if (i == 0) {
			return true;
		} else {
			return false;
		}
		
	}
	
	
	public static boolean checkTCPPortIsInUse( int port ) {
		
		return checkPortIsInUse( "tcp" , port );
		
	}
	
	public static boolean checkUDPPortIsInUse( int port ) {
		
		return checkPortIsInUse( "udp" , port );
	}
	
	
	public static boolean checkPortIsInUse(String  protocal, int port ) {
		try {
			
			if( "tcp".equals(protocal) ){
				try {
					Socket socket = new Socket( InetAddress.getByName("127.0.0.1"), port);
					socket.close();
					return true;  
				} catch (Exception e) {
					return false;
				}
			}
			
			if( OSinfo.isWindows() ){
				
				String cmd = "cmd.exe /c netstat -ano | findstr \"" + port+"\"";
				Runtime runtime = Runtime.getRuntime();
				Process exec = runtime.exec(cmd);
				InputStream inputStream = exec.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				byte[] buffer = new byte[256];  
			    int len = -1;  
			    while ((len = inputStream.read(buffer)) != -1) {  
			    	baos.write(buffer, 0, len);
			    }
			    String result = new String( baos.toByteArray() );
			    baos.close();
			    
			    if( result!=null ){
			    	String lowerCaseResult = result.toLowerCase();
			    	String portStr = port+"";
			    	int portStrlength = portStr.length();
			    	String[] split = lowerCaseResult.split("\r");
			    	for( int i=0 ; i<split.length ; i++  ){
			    		String tmpLine = split[i];
			    		int indexOf = tmpLine.indexOf(protocal);
			    		if( indexOf != -1 ){
			    			int portIndex = tmpLine.indexOf(portStr);
			    			String beforeChar = tmpLine.substring( portIndex-1  , portIndex);
			    			String nextChar = tmpLine.substring( portIndex+portStrlength , portIndex +portStrlength+1);
			    			if( ":".equals(beforeChar) &&  "".equals(nextChar.trim()) ){
			    				return true;
			    			}
			    		}
			    	}
			    }
			}else if( OSinfo.isLinux() ){
				
			}
		} catch (Exception e) {
			logger.error("", e);
		}
		return false;
	}
	
	
	
	public static void main(String[] args) throws IOException, InterruptedException {
		
//		String userDir = System.getProperty("user.dir");
//		System.out.println( userDir.replaceAll("\\\\", "/") );
//		boolean runScript = runScript("bin", "startnms");
//		System.out.println( runScript  );
		
		System.out.println(  checkUDPPortIsInUse(61445)  );
		
//		System.out.println(   checkTCPPortIsInUse(8889)   );
		
	}
	
}
